package com.bigdata.utils;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * Created by yangl on 2017/8/30.
 */
public class FreeMarkerUtil {
    /**
     * 通过模板生成数据
     *
     * @param file
     * @param ftl
     * @param map
     * @return
     * @throws java.io.IOException
     * @throws freemarker.template.TemplateException
     */
    public static String toStringTem(String file, String ftl, Map map) throws IOException, TemplateException {
        Configuration conf = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        conf.setDirectoryForTemplateLoading(new File(file));
        conf.setObjectWrapper(new DefaultObjectWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
        conf.setLocale(Locale.CHINA);
        conf.setDefaultEncoding("UTF-8");
        conf.setClassicCompatible(true);
        conf.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
        Template tem = conf.getTemplate(ftl);
        StringWriter writer = new StringWriter();
        tem.process(map, writer);
        return writer.toString();
    }

    public static void main(String[] args) throws IOException, TemplateException {
        Map<String, String> p = new HashMap<>();
        p.put("basePath", "ccc");
        System.out.println(toStringTem("E:\\lly\\java\\springboot\\springbigdata\\src\\main\\resources\\templates\\error", "404.html", p));
    }
}
